package com.loren.demo07.sockjs.controller;

import com.loren.demo07.sockjs.form.SockJsMessageForm;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Slf4j
@Controller
@AllArgsConstructor
public class SockJsController {

    private final SimpMessagingTemplate simpMessagingTemplate;

    @GetMapping
    public String index(@RequestParam("client_id") String clientId, Model model) {
        model.addAttribute("clientId", clientId);
        return "sockjs";
    }

    @MessageMapping("/message/send")
    public void sendMessage(SockJsMessageForm form) {
        this.simpMessagingTemplate.convertAndSendToUser(form.getClientId(), "/message", form.getContent());
    }
}
